<?php

class UserController extends Zend_Controller_Action
{

    private $defStartPower = 100;

    private $defWealth = 50000;

    private $defAP = 100;

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        $this->_redirect('user/home');
    }

    public function homeAction()
    {
    	$auth = Zend_Auth::getInstance();
        if ($auth->hasIdentity()) 
        {
            $username = $auth->getIdentity()->username; 
            $user_id = $auth->getIdentity()->id; 
         	$this->view->message = $username;
           
            //1. check if user its new and set new params
            $result = $this->checkIfUserIsNew($user_id);
            //2. check if user its activated
            $result = $this->checkIfUserActivated($user_id);
            if( !$result ) //new user and race not selected
            {
            	$form = new Application_Form_RoundSettings();
	         	$this->view->roundSettingsForm = $form;
	        	//colect data from form and insert default value
	        	if($this->getRequest()->isPost())
	        	{
	        		//prepare player for starting of the round
	    			if($form->isValid($_POST))
	    			{
			        	$race_name = $form->getValue('race');
			        	$alias = $form->getValue('alias');
			            //3. set race and class if the user just started the round          
				        $result = $this->setDefaultStartValues($user_id, $race_name, $alias);
				        if( !$result )
				        {
				        	$this->view->errorMessage = "Internal error! Error while start the game for the new user!";
				          	return;
				        }
				        $this->_redirect('user/home');	
	    			}
	        	}
            }
        }
        else {
        	$this->_redirect('authentication/login');	
        }
        
    }

    private function checkIfUserIsNew($user_id)
    {
    	$roundSettingsTbl = new Application_Model_RoundSettingsTbl();

    	$result = $roundSettingsTbl->checkIfUserExists($user_id);
    	//if user does not exist on round setting it will be inserted
    	if(!$result)
    	{
    		$data = array 	(
    						'user_fk' => $user_id,
    						'alias' => $user_id,
    						'race_fk' => 0,
    						'class_fk' => 0
    						);
    		$roundSettingsTbl->insert($data);
    		return true;
    	}
    	return false;
    }

    private function checkIfUserActivated($user_id)
    {
	
		$roundSettingsTbl = new Application_Model_RoundSettingsTbl();
		if( $roundSettingsTbl->checkIfClassAndRaceAreSelected($user_id) ) //return true if race is selected
     	{
     		return true; // race selected  
     	}
     	else
     	{		
	   		return false; //race not selected
    	
   	 }
    }

    private function setDefaultStartValues($user_id, $race_name, $alias)
    {
    	$roundSettingsTbl = new Application_Model_RoundSettingsTbl();
        $raceTbl = new Application_Model_RaceTbl();
        //$classTbl = new Application_Model_HeroClassTbl();
        //check if class and race selected. if not selected function return true
       
        //1.set class and race for new user
		$row = $roundSettingsTbl->fetchRow($roundSettingsTbl->select()->where('user_fk = ?', $user_id));
		//Change the value of one or more column
		//INFO FOR ALPHA VERSION THE CLASS WILL BE AUTOMATICALY SELECTED FROM THE RACE
		$result = $raceTbl->getRaceIDByRaceName($race_name);
		$row->race_fk = $result['id'];
		$row->class_fk = $result['class_fk'];
				
		$row->alias = $alias;
		//UPDATE the row in the database with new values
		$row->save();
					
		//2.  we need to set initial values for start of the game
		$result = $this->setInitialValuesForPlayer($user_id, $row->class_fk, $row->race_fk);
		if(!$result)
		{
			$this->view->errorMessage = "Internal error! Unable to set initial values for start of the game!";
			return;
		}

    	return true;
    }

    private function setInitialValuesForPlayer($user_id, $class_fk, $race_fk)
    {
		$lightUserArmy = new Application_Model_LightUserArmyTbl();
		$darkUserArmy = new Application_Model_DarkUserArmyTbl();
		$raceUnits = new Application_Model_RaceUnits();
		$userStats = new Application_Model_UserStatsTbl();
		
		$result = $raceUnits->getUnitsPowerForRaceID($race_fk);
		$result2 = $raceUnits->getUnitsIncomeForRaceID($race_fk);
		$nrLvl1 = 0;
		$powerLvl1 = $result['lvl1'];
		$incomeLvl1 = $result2['lvl1'];
		
		//calc and set power,income,wealth, ap for user_stats;
		$nrLvl1 = round($this->defStartPower / $powerLvl1);
		$powerTotal = $nrLvl1 * $powerLvl1;
		$incomeCalc = $nrLvl1 * $incomeLvl1;
		$wealthDefault = $this->defWealth;
		$apDefault = $this->defAP;
		$popDefault = $nrLvl1;
		
		//1. instert into user_stats initial values
		$result = $userStats->checkIfUserExists($user_id);
		//if exist delete row for user_id
		if ($result)
		{
			$row = $userStats->fetchRow('user_fk = ?',$user_id);
			// DELETE this row
			$row->delete();
		}
		else //insert new values 
		{
			$data = array 	(
    						'user_fk' => $user_id,
    						'power' => $powerTotal,
    						'income' => $incomeCalc,
							'wealth' => $wealthDefault,
    						'attack_points' => $apDefault,
							'current_population' => $popDefault,
							'total_population' => $popDefault
    						);
    		$userStats->insert($data);
		}
		
		//2. insert into dark/light_army_units intial values	
		if( $class_fk == 1 )// the race is from light class
		{
			$result = $lightUserArmy->checkIfUserExists($user_id);
			//if exist delete row for user_id
			if ($result)
			{
				$row = $lightUserArmy->fetchRow('user_fk = ?',$user_id);
				// DELETE this row
				$row->delete();
			}
			else //insert new values 
			{
				$data = array 	(
	    						'user_fk' => $user_id,
	    						'lvl1' => $nrLvl1
	    						);
	    		$lightUserArmy->insert($data);
			}			
		}
		else // the race is from dark class
		{
			$result = $darkUserArmy->checkIfUserExists($user_id);
			//if exist delete row for user_id
			if ($result)
			{
				$row = $darkUserArmy->fetchRow('user_fk = ?',$user_id);
				// DELETE this row
				$row->delete();
			}
			else //insert new values 
			{
				$data = array 	(
	    						'user_fk' => $user_id,
	    						'lvl1' => $nrLvl1
	    						);
	    		$darkUserArmy->insert($data);
			}	
		}
				
		return true;
    }

    public function settingsAction()
    {
    	$usersTbl = new Application_Model_UsersTbl();
        $auth = Zend_Auth::getInstance();
        $form = new Application_Form_UserSettings();
        if ($auth->hasIdentity()) 
        {
            $username = $auth->getIdentity()->username; 
            $user_id = $auth->getIdentity()->id; 
         	
         	$row = $usersTbl->fetchRow($usersTbl->select()->where('username = ?', $username));
			if ( $row != null )
			{
				$this->view->settingsForm = $form;
    			if($this->getRequest()->isPost())
    			{
    			if($form->isValid($_POST))
    				{
    					$data = $form->getValues();	
		    			if( $data['firstname'] != '' )
		    				$row->firstname = $data['firstname'];
		    			if( $data['lastname']  != '' )
		    				$row->lastname = $data['lastname'];
		    			if( $data['email'] != ''  )
		    				$row->email = $data['email'];
		    				
		    			if(  $data['newPassword'] != '' )
		    			{
		    				if( $data['newPassword'] != $data['confirmPassword'] )
		    				{
    							$this->view->errorMessage = "Password and confirm password don't match! ";
    							return;
    						}
		    				$row->password = $data['newPassword'];
		    				unset($data['confirmPassword']);
		    			}
						//UPDATE the row in the database with new values
						$row->save();	
						$this->_redirect('user/home');
    				}
    			}	
			}
        }
        else {
        	$this->_redirect('authentication/login');	
        }
       	
    }

}

 

						



